package cn.laixueit.service.impl;

import cn.laixueit.mapper.BrandMapper;
import cn.laixueit.pojo.item.Brand;
import cn.laixueit.pojo.result.PageResult;
import cn.laixueit.service.BrandService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BrandServceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Override
    public PageResult<Brand> findPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        PageResult<Brand> result = new PageResult<>();

        Page<Brand> p = new Page<>(page, rows);
        QueryWrapper<Brand> wrapper = getCondition(key,sortBy,desc);
        IPage<Brand> brandIPage = page(p, wrapper);
        result.setItems(brandIPage.getRecords());
        result.setTotal(Long.valueOf(brandIPage.getTotal()).intValue());
        return result;
    }

    // 事务
    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {
        //保存品牌
        save(brand);
        // 保存分类
        for (Long cid : cids) {
            brandMapper.saveBrandAndCategoryId(brand.getId(),cid);
        }
    }

    @Override
    public List<Brand> findBrandListByCategoryId(Long cid) {
        List<Brand> brandList = brandMapper.findBrandListByCategoryId(cid);
        return brandList;
    }

    private QueryWrapper<Brand> getCondition(String key, String sortBy, Boolean desc) {
        QueryWrapper<Brand> wrapper = new QueryWrapper<>();
        if(key!=null && !"".equals(key)){
            wrapper.like("name",key);
        }
        if(sortBy!=null && !"".equals(sortBy)){
            if(!desc){
                wrapper.orderByDesc(sortBy);
            }
        }
        return wrapper;
    }


}
